package com.jfinal.weixin.lbs;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;

public class WeixinUserInfoInterceptor implements Interceptor {
    Log logger = Log.getLog(this.getClass());

    @Override
    public void intercept(Invocation ai) {
        logger.info("Before invoking " + ai.getActionKey());
        WeixinApiController controller = (WeixinApiController) ai.getController();
        String code = controller.getPara("code");
        if (ai.getController().getSessionAttr("userInfo") == null && code != null) {
            SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(controller.getApiConfig().getAppId(), controller.getApiConfig().getAppSecret(), code);
            ApiResult userInfo = null;
            if (snsAccessToken.getErrorCode() == null) {
                userInfo = SnsApi.getUserInfo(snsAccessToken.getAccessToken(), snsAccessToken.getOpenid());
            } else {
                throw new RuntimeException(snsAccessToken.toString());
            }
            if (userInfo.getErrorCode() == null) {
                ai.getController().setSessionAttr("userInfo", userInfo);
            } else {
                throw new RuntimeException(userInfo.toString());
            }
        }
        ai.invoke();
        logger.info("After invoking " + ai.getActionKey());
    }
}
